﻿
using Manage.Traceability.Domain;
using Manage.Traceability.ErrorCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Manage.Traceability.Api.Controllers
{
    /// <summary>
    /// 图片控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ImgsController : ControllerBase
    {
        private readonly ISqlSugarClient db;

        public ImgsController(ISqlSugarClient db)
        {
            this.db = db;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Imgs(IFormFile file)
        {
            var path = Directory.GetCurrentDirectory() + "/wwwroot/pic/" + file.FileName;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fs);
            }
            return Ok("http://localhost:5002/pic/" + file.FileName);
        }
        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="imgs"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult<int>AddImgs(ImgsModel imgs)
        {
            int r1 = db.Insertable(imgs).ExecuteCommand(); //都是参数化实现
            if (r1 > 0)
            {
                return ApiResult<int>.Success("添加图片成功", r1);
            }
            else
            {
                return ApiResult<int>.Fail("添加图片失败");
            }
        }
        /// <summary>
        /// 图片反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiResult<ImgsModel>GetImgs(int id)
        {
            var list = db.Queryable<ImgsModel>().Where(it => it.Imgsid == id).OrderBy(it => it.Imgsid, OrderByType.Desc).First();
            return ApiResult<ImgsModel>.Success("图片显示成功",list);
        }
    }
}
